package com.ruoyi.project.zxbd.controller;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.zx.PageData;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.zxbd.mapper.LeaveapplyMapper;
import com.ruoyi.project.zxbd.service.impl.LeaveApplyServiceImpl;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/bd/function/leaveapply")
public class LeaveApplyController extends BaseController {
    @Autowired
    private LeaveApplyServiceImpl leaveApplyService;
    @Autowired
    private LeaveapplyMapper leaveapplyMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 获取当前登录用户的名称，用于添加请假时姓名自动显示
     * @return username
     */
    @GetMapping("/getName")
    public String getUserName(){
        LoginUser loginUser = getLoginUser();
        return loginUser.getUsername();
    }
    /**
     * 查询请假列表
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:list')")
    @GetMapping("/list")
    public TableDataInfo list(){
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = leaveApplyService.selectLeaveApplyList(pd);
        return getDataTable(list);
    }

    /**
     * 查询部门领导列表
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:list')")
    @GetMapping("/leader_list")
    public TableDataInfo deptLeaderList(){
        startPage();
        List<PageData> deptLeaderList = leaveapplyMapper.selectDeptLeaderList();
        return getDataTable(deptLeaderList);
    }

    /**
     * 点击办理
     * 办理请假：包括部门领导审批和人事审批
     * @return
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:query')")
    @GetMapping( "/get/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id){
        //PageData pd=new PageData();
        PageData pageData=leaveApplyService.selectLeaveApplyById(id);
        return AjaxResult.success(pageData);
    }

    /**
     * 新增请假
     * @param leaveapply
     * @return
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:add')")
    @PostMapping("/add")
    public AjaxResult addSave(@RequestBody PageData leaveapply){
        leaveapply.put("apply_time",new Date());
        return toAjax(leaveApplyService.insertLeaveApply(leaveapply));
    }

    /**
     * 更新请假
     * @param leaveapply
     * @return
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:update')")
    @PutMapping("/update")
    public AjaxResult update(@RequestBody PageData leaveapply){
        return toAjax(leaveApplyService.updateLeaveApply(leaveapply));
    }

    /**
     * 删除请假
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable("ids") String ids){
        return toAjax(leaveApplyService.deleteLeaveApplyByIds(ids));
    }

    /**
     * 导出请假列表
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:export')")
    @PostMapping("/export")
    public AjaxResult export(@RequestBody PageData leaveapply){
        leaveapply.put("user_id","");
        List<PageData> list = leaveApplyService.selectLeaveApplyList(leaveapply);
        ExcelUtil<PageData> util = new ExcelUtil<PageData>(PageData.class);
        return util.exportExcel(list, "请假数据");
    }

    /**
     * 撤销：强行结束掉一个流程
     * @param taskId:当前任务id
     * @return
     */
    @GetMapping(value = "/forceEnd/{task_id}")
    @ResponseBody
    public AjaxResult forceEnd(@PathVariable("task_id") String taskId) {
        Task t = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processDefinitionId = runtimeService.createProcessInstanceQuery().processInstanceId(t.getProcessInstanceId()).singleResult().getProcessDefinitionId();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        // 寻找流程实例当前任务的activeId
        Execution execution = runtimeService.createExecutionQuery().executionId(t.getExecutionId()).singleResult();
        String activityId = execution.getActivityId();
        FlowNode currentNode = (FlowNode)bpmnModel.getMainProcess().getFlowElement(activityId);
        // 创建结束节点和连接线
        EndEvent end = new EndEvent();
        end.setName("强制结束");
        end.setId("forceEnd");
        List<SequenceFlow> newSequenceFlowList = new ArrayList<SequenceFlow>();
        SequenceFlow newSequenceFlow = new SequenceFlow();
        newSequenceFlow.setId("newFlow");
        newSequenceFlow.setSourceFlowElement(currentNode);
        newSequenceFlow.setTargetFlowElement(end);
        newSequenceFlowList.add(newSequenceFlow);
        // 备份原有方向
        List<SequenceFlow> dataflows = currentNode.getOutgoingFlows();
        List<SequenceFlow> oriSequenceFlows = new ArrayList<SequenceFlow>();
        oriSequenceFlows.addAll(dataflows);
        // 清空原有方向
        currentNode.getOutgoingFlows().clear();
        // 设置新方向
        currentNode.setOutgoingFlows(newSequenceFlowList);
        // 完成当前任务
        taskService.addComment(taskId, t.getProcessInstanceId(), "comment", "撤销流程");
        taskService.complete(taskId);
        // 恢复原有方向
        currentNode.setOutgoingFlows(oriSequenceFlows);
        return AjaxResult.success();
    }

}
